package com.ec.mn.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ec.api.client.UserClient;
import com.ec.common.domain.Result;

import com.ec.common.exception.BadRequestException;
import com.ec.mn.entity.HealthRecord;
import com.ec.mn.service.HealthRecordService;
import com.ec.mn.service.NotificationService;
import com.ec.mn.service.WarningRulesService;
import com.ec.mn.service.impl.HealthRecordServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 健康数据记录控制器
 */
@Api(tags = "健康数据记录管理")
@RestController
@RequestMapping("/health-records")
@RequiredArgsConstructor
public class HealthRecordController {
    private final HealthRecordService healthRecordService;
    private final NotificationService notificationService;
    private final WarningRulesService warningRulesService;
    private final UserClient userClient;

    /**
     * 新增健康数据记录
     */
    @ApiOperation("新增健康数据记录")
    @PostMapping("/add")
    public Result<HealthRecord> addHealthRecord(@RequestBody HealthRecord healthRecord) {
        // 判断用户是否存在
        Result<Boolean> userResult = userClient.checkUserExists(healthRecord.getElderlyUserId());
        if (!userResult.getData()) {
            return Result.error("用户不存在");
        }
        // 用户角色判断
        Result<Long> elderlyRoleResult = userClient.getUserRoleId(healthRecord.getElderlyUserId());
        if (elderlyRoleResult.getData() == null || elderlyRoleResult.getData() != 2L) {
            return Result.error("老人用户ID无效或角色不正确");
        }

        // 设置创建时间
        healthRecord.setRecordedAt(LocalDateTime.now());
        try {
            warningRulesService.checkAndWarn(healthRecord);
            if(healthRecord.getIsAbnormal()==1){
                notificationService.add(healthRecord, warningRulesService.checkAndWarn(healthRecord));
            }
            boolean success = healthRecordService.save(healthRecord);
            if (success) {
                return Result.ok(healthRecord);
            } else {
                return Result.error("新增数据记录失败");
            }

        } catch (Exception e) {
            return Result.error("新增数据记录失败:"+e.getMessage());
        }
    }


    /**
     * 根据ID删除健康数据记录
     */
    @ApiOperation("根据ID删除健康数据记录")
    @GetMapping("/delete")
    public Result<String> deleteHealthRecord(@ApiParam("记录ID") @RequestParam Long id) {
        try{
            boolean success = healthRecordService.removeById(id);
            if (success) {
                return Result.ok("删除成功");
            } else {
                return Result.error("删除失败");
            }

        }catch (Exception e) {
            return Result.error("删除记录失败:"+e.getMessage());
        }

    }

    /**
     * 批量删除健康数据记录
     */
    @ApiOperation("批量删除健康数据记录")
    @PostMapping("/batch")
    public Result<String> batchDeleteHealthRecord(@RequestBody List<Long> ids) {
        try{
            boolean success = healthRecordService.removeByIds(ids);
            if (success) {
                return Result.ok("批量删除成功");
            } else {
                return Result.error("批量删除失败");
            }

        }catch (Exception e) {
            return Result.error("批量删除失败:"+e.getMessage());
        }

    }

    /**
     * 更新健康数据记录
     */
    @ApiOperation("更新健康数据记录")
    @PostMapping("/update")
    public Result<HealthRecord> updateHealthRecord(@RequestBody HealthRecord healthRecord) {
        try{
            if(healthRecord.getIsAbnormal()==1){
                notificationService.add(healthRecord, warningRulesService.checkAndWarn(healthRecord));
            }
            boolean success = healthRecordService.updateById(healthRecord);
            if (success) {
                return Result.ok(healthRecord);
            } else {
                return Result.error("更新失败");
            }
        }catch (Exception e) {
            return Result.error("更新失败:"+e.getMessage());
        }

    }

    /**
     * 根据ID查询健康数据记录
     */
    @ApiOperation("根据ID查询健康数据记录")
    @GetMapping("/search")
    public Result<HealthRecord> getHealthRecordById(@ApiParam("记录ID") @RequestParam Long id) {
        try{
            HealthRecord healthRecord = healthRecordService.getById(id);
            if (healthRecord != null) {
                return Result.ok(healthRecord);
            } else {
                return Result.error("记录不存在");
            }
        }catch  (Exception e) {
            return Result.error("查询失败:"+e.getMessage());
        }

    }

    /**
     * 分页查询健康数据记录
     */
    @ApiOperation("分页查询健康数据记录")
    @GetMapping("/page")
    public Result<Page<HealthRecord>> getHealthRecordPage(
            @ApiParam("页码") @RequestParam(defaultValue = "1") Integer current,
            @ApiParam("每页大小") @RequestParam(defaultValue = "10") Integer size,
            @ApiParam("老人用户ID") @RequestParam(required = false) Long elderlyUserId,
            @ApiParam("数据类型") @RequestParam(required = false) String recordType,
            @ApiParam("是否异常") @RequestParam(required = false) Integer isAbnormal,
            @ApiParam("开始时间") @RequestParam(required = false) String startTime,
            @ApiParam("结束时间") @RequestParam(required = false) String endTime,
            @ApiParam("管理员用户ID") @RequestParam(required = false) Long AdminId) {
        
        Page<HealthRecord> page = new Page<>(current, size);
        QueryWrapper<HealthRecord> queryWrapper = new QueryWrapper<>();
        
        // 添加查询条件
        if (elderlyUserId != null) {
            queryWrapper.eq("elderly_user_id", elderlyUserId);
        }
        if (recordType != null && !recordType.trim().isEmpty()) {
            queryWrapper.eq("record_type", recordType);
        }
        //不知道为什么，这个老是出错
        if (isAbnormal != null) {
            queryWrapper.eq("is_abnormal", isAbnormal);
        }
        
        // 时间范围查询
        if (startTime != null && !startTime.trim().isEmpty()) {
            queryWrapper.ge("recorded_at", startTime);
        }
        if (endTime != null && !endTime.trim().isEmpty()) {
            queryWrapper.le("recorded_at", endTime);
        }
        if (AdminId != null) {
            queryWrapper.eq("created_by_admin_id", AdminId);
        }
        // 按记录时间倒序排列
        queryWrapper.orderByDesc("recorded_at");
        
        Page<HealthRecord> result = healthRecordService.page(page, queryWrapper);
        return Result.ok(result);
    }


    /**
     * 根据老人用户ID查询健康数据记录
     */
    @ApiOperation("根据老人用户ID查询健康数据记录")
    @GetMapping("/elderly")
    public Result<List<HealthRecord>> getHealthRecordsByElderlyUserId(
            @ApiParam("老人用户ID") @RequestParam Long elderlyUserId) {
        QueryWrapper<HealthRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("elderly_user_id", elderlyUserId);
        queryWrapper.orderByDesc("recorded_at");
        
        List<HealthRecord> records = healthRecordService.list(queryWrapper);
        return Result.ok(records);
    }

    /**
     * 查询异常健康数据记录
     */
    @ApiOperation("查询异常健康数据记录")
    @GetMapping("/abnormal")
    public Result<List<HealthRecord>> getAbnormalHealthRecords(
            @ApiParam("老人用户ID") @RequestParam(required = false) Long elderlyUserId) {
        QueryWrapper<HealthRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_abnormal", 1);
        
        if (elderlyUserId != null) {
            queryWrapper.eq("elderly_user_id", elderlyUserId);
        }
        
        queryWrapper.orderByDesc("recorded_at");
        List<HealthRecord> records = healthRecordService.list(queryWrapper);
        return Result.ok(records);
    }

    /**
     * 根据数据类型查询健康数据记录
     */
    @ApiOperation("根据数据类型查询健康数据记录")
    @GetMapping("/type/{recordType}")
    public Result<List<HealthRecord>> getHealthRecordsByType(
            @ApiParam("数据类型") @PathVariable String recordType,
            @ApiParam("老人用户ID") @RequestParam(required = false) Long elderlyUserId) {
        QueryWrapper<HealthRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("record_type", recordType);
        
        if (elderlyUserId != null) {
            queryWrapper.eq("elderly_user_id", elderlyUserId);
        }
        
        queryWrapper.orderByDesc("recorded_at");
        List<HealthRecord> records = healthRecordService.list(queryWrapper);
        return Result.ok(records);
    }

    /**
     * 获取所有健康数据记录
     */
    @ApiOperation("获取所有健康数据记录")
    @GetMapping("/all")
    public Result<List<HealthRecord>> getAllHealthRecords() {
        QueryWrapper<HealthRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("recorded_at");
        List<HealthRecord> records = healthRecordService.list(queryWrapper);
        return Result.ok(records);
    }


    /**
     * 获取最近7天的健康数据记录
     */
    @ApiOperation("获取最近7天的健康数据记录")
    @GetMapping("/recent")
    public Result<List<HealthRecord>> getRecentHealthRecords(
            @ApiParam("老人用户ID") @RequestParam(required = false) Long elderlyUserId) {
        QueryWrapper<HealthRecord> queryWrapper = new QueryWrapper<>();
        if (elderlyUserId != null) {
            queryWrapper.eq("elderly_user_id", elderlyUserId);
        }
        
        // 查询最近7天的记录
        LocalDateTime sevenDaysAgo = LocalDateTime.now().minusDays(7);
        queryWrapper.ge("recorded_at", sevenDaysAgo);
        queryWrapper.orderByDesc("recorded_at");
        
        List<HealthRecord> records = healthRecordService.list(queryWrapper);
        return Result.ok(records);
    }
} 